<template>
    <div class="dataView">
        <el-row class="flex">
            <div class="main_left radius8 bgf" style="min-width: 204px;">
                <el-tree :data="data" node-key="id" :default-expand-all="true" :highlight-current="true"
                    :default-checked-keys="[9]" :props="defaultProps" @node-click="handleNodeClick" />
            </div>
            <div class="main_right c3 fs20">
                <el-row class="main-right-tit">
                    <el-col :span="12" style="padding-left: 18px;">设备SK234</el-col>
                    <el-col :span="12">
                        <el-row justify="end" class="c6" style="margin-right: 35px;">
                            <svg-icon name="temp_grey" top="6" right="4"></svg-icon><span class="fs12"
                                style="padding: 10px 12px;">温度</span>
                            <svg-icon name="humidity_blue" top="6" right="4"></svg-icon><span class="fs12"
                                style="padding: 10px 12px;">湿度</span>
                        </el-row>
                    </el-col>
                </el-row>

                <el-row :gutter="20" class="main-right-center">

                    <el-col :span="12" class="main-right-center_l">
                        <!-- 左边盒子 -->
                        <el-row style="height: 85%;padding-top: 20px;" class="bgf radius-top">
                            <!-- 温度box -->
                            <el-col :span="12" class="temp_box" style="border-right: 1px solid #E4E7ED;">
                                <el-row style="padding: 0 30px;box-sizing: border-box;">
                                    <el-col :span="12">温度</el-col>
                                    <el-col :span="12">
                                        <el-row justify="end">
                                            <el-button :icon="Sunrise" size="small" type="primary">设置</el-button>
                                        </el-row>
                                    </el-col>
                                </el-row>
                                <div id="temperature" class="cav-box"></div>
                            </el-col>
                            <!-- 湿度box -->
                            <el-col :span="12" class="temp_box">
                                <el-row style="padding: 0 30px;box-sizing: border-box;">
                                    <el-col :span="12">湿度</el-col>
                                    <el-col :span="12">
                                        <el-row justify="end">
                                            <el-button :icon="Sunrise" size="small" type="primary">设置</el-button>
                                        </el-row>
                                    </el-col>
                                </el-row>
                                <div id="humidity" class="cav-box"></div>
                            </el-col>
                        </el-row>

                        <el-row style="height: 15%;" class="flex-center-center bgf radius-bot">
                            更新时间: {{updateTime}}
                        </el-row>
                    </el-col>
                    <!-- 右边盒子 -->
                    <el-col :span="12" class="bgf main-right-center_r radius8">
                        <el-row style="height: 39px;margin: 16px 25px;">
                            <el-col :span="12">最近趋势</el-col>
                            <el-col :span="12">
                                <el-row justify="end" class="c6">
                                    <svg-icon name="temp_red" top="6" right="4"></svg-icon><span class="fs12"
                                        style="padding: 10px 12px;">温度</span>
                                    <svg-icon name="humidity_blue" top="6" right="4"></svg-icon><span class="fs12"
                                        style="padding: 10px 12px;">湿度</span>
                                </el-row>
                            </el-col>
                        </el-row>
                        <el-row>
                            <div id="tempAndHumLine" class="radius8 cav-box"></div>
                        </el-row>
                    </el-col>
                </el-row>
                <!-- bottom -->
                <el-row class="main-right-bottom radius8 bgf" style="padding: 0 25px;box-sizing:border-box">
                    <el-row style="width: 100%;height: 39px;margin: 16px 0;">
                        <el-col :span="12">数据统计</el-col>
                        <el-col :span="12">
                            <el-row justify="end" class="c6">
                                <svg-icon name="temp_red" top="6" right="4"></svg-icon><span class="fs12"
                                    style="padding: 10px 12px;">温度</span>
                                <svg-icon name="humidity_blue" top="6" right="4"></svg-icon><span class="fs12"
                                    style="padding: 10px 12px;">湿度</span>
                            </el-row>
                        </el-col>
                    </el-row>
                    <el-row style="width: 100%;">
                        <template v-for="(item, index) in selectTime" :key="item">
                            <div class="select-time text-align-center cm bgf radius20"
                                :class="{ 'selBgc': index == indexs }">{{ item.name }}</div>
                        </template>
                    </el-row>
                    <el-row style="width: 100%;height: 100%">
                        <div id="dataStatis" style="width: 100%;height: 70%;margin: 0 auto;"></div>
                    </el-row>
                </el-row>
            </div>
        </el-row>
        <!-- 设置弹窗 -->
        <el-dialog v-model="dialogFormVisible" title="设置">
            <div style="border-top: 1px solid #ccc;padding-top: 15px;">
                <div class="flex" style="margin-left: 40px;margin-bottom: 10px;" v-for="(items, index) in iptNum"
                    :key="items">
                    <span style="padding-top: 4px;">报警值：</span>
                    <el-select v-model="value" class="m-2" placeholder="请选择范围">
                        <el-option v-for="item in options" :key="item.value" :value="item.value"
                            @change="selchange(item)" />
                    </el-select>
                    <el-input v-model="items.value" placeholder="请输入数值" type="number"
                        style="width: 200px;margin-left: 15px;" />
                    <el-icon color="#409EFF" v-if="index == 0" :size="25" class="icon_el" @click="pushList">
                        <CirclePlus />
                    </el-icon>
                    <el-icon color="#FF4D4F" v-else :size="25" class="icon_el" @click="delList(index)">
                        <Remove />
                    </el-icon>
                </div>
            </div>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="setBtn">确定</el-button>
                </span>
            </template>
        </el-dialog>

    </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance,onBeforeMount } from "vue";
import * as echarts from 'echarts';
import { Sunrise, CirclePlus, Remove } from '@element-plus/icons-vue';
import { getDeviceDataLatest,getDeviceDataHisList } from "@/api";
import { formatTime } from "@/utils/util";

const dialogFormVisible = ref(false);
const { proxy } = getCurrentInstance();
const indexs = ref(0);
const value = ref('');
const updateTime = ref('');
// 获取最新的温湿度数据
const echartList1 = ref({});
// 历史温湿度数据(最近趋势)
const echartList2 = ref({});
// 数据统计(指定时间)
const echartList3 = ref({});

onBeforeMount(() => {
    // getNewestList();
    // getHisList();
    // getHisSelList();
})
// 获取最新的温湿度数据
const getNewestList = async () => {
    echartList1.value = await getDeviceDataLatest();
    updateTime.value = formatTime(new Date(echartList1.value.create_time));
    return echartList1;
}
// 获取历史温湿度数据(最近趋势)
const getHisList = async () => {
    let pdata = {
        perid: '10m',
        duration: '1h',
    }
    echartList2.value = await getDeviceDataHisList(pdata);
    // console.log('最近趋势',echartList2.value)
    return echartList2;
}
// 获取历史温湿度数据(最近趋势)
const getHisSelList = async () => {
    let pdata = {
        perid: '1h',
        duration: '1d',
    }
    echartList3.value = await getDeviceDataHisList(pdata);
    console.log('数据统计',echartList3.value)
    return echartList3;
}

const iptNum = ref([
    {
        value: '',
    }
])

const options = [
    {
        value: '大于',
    },
    {
        value: '等于',
    },
    {
        value: '小于',
    },
]
// 下拉选择触发
const selchange = (item) => {
    console.log('sel', item)
}
const pushList = () => {
    if (iptNum.value.length < 3) {
        iptNum.value.push({
            value: '',
        })
    }
}
const delList = (index) => {
    iptNum.value.splice(index,1);
}
const setBtn = () => {
    dialogFormVisible.value = false
}
// 时间类型选择
const selectTime = [
    {
        name: '24小时',
        perid: '1h',
        duration: '1d',
    },
    {
        name: '48小时',
        perid: '2h',
        duration: '2d',
    },
    {
        name: '一星期',
        perid: '1d',
        duration: '7d',
    },
    {
        name: '半个月',
        perid: '1d',
        duration: '15d',
    },
    {
        name: '一个月',
        perid: '2d',
        duration: '30d',
    },
    {
        name: '6个月',
        perid: '10d',
        duration: '180d',

    },
    {
        name: '自定义',
    },
]
// 加载4个图表
onMounted(() => {
    getNewestList().then((res) => {
        temperatureInit(res);
        humidityInit(res);
    })
    getHisList().then((res) => {
        tempAndHumLineInit(res);
    })
    getHisSelList().then((res) => {
        dataStatisInit(res);
    })
    
})
// 温度仪表盘
const temperatureInit = (res) => {
    let chartDom = document.getElementById('temperature');
    let myChart = proxy.$echarts.init(chartDom);
    let ro = new ResizeObserver((entries) => {
        myChart.resize();
    });
    ro.observe(chartDom);
    let option;

    option = {
        series: [
            {
                type: 'gauge',
                center: ['50%', '60%'],
                radius: '60%',
                startAngle: 200,
                endAngle: -20,
                min: 0,
                max: 60,
                splitNumber: 12,
                itemStyle: {
                    color: '#FFAB91'
                },
                progress: {
                    show: true,
                    width: 30
                },
                pointer: {
                    show: false
                },
                axisLine: {
                    lineStyle: {
                        width: 30
                    }
                },
                axisTick: {
                    distance: -45,
                    splitNumber: 5,
                    lineStyle: {
                        width: 2,
                        color: '#999'
                    }
                },
                splitLine: {
                    distance: -52,
                    length: 14,
                    lineStyle: {
                        width: 3,
                        color: '#999'
                    }
                },
                axisLabel: {
                    distance: -8,
                    color: '#999',
                    fontSize: 15
                },
                anchor: {
                    show: false
                },
                title: {
                    show: false
                },
                detail: {
                    valueAnimation: true,
                    width: '40%',
                    lineHeight: 30,
                    borderRadius: 8,
                    offsetCenter: [0, '-15%'],
                    fontSize: 20,
                    fontWeight: 'bolder',
                    formatter: '{value} °C',
                    color: 'inherit'
                },
                data: [
                    {
                        value: res.value.temperature
                    }
                ]
            },
            {
                type: 'gauge',
                center: ['50%', '60%'],
                radius: '60%',
                startAngle: 200,
                endAngle: -20,
                min: 0,
                max: 60,
                itemStyle: {
                    color: '#FD7347'
                },
                progress: {
                    show: true,
                    width: 8
                },
                pointer: {
                    show: false
                },
                axisLine: {
                    show: false
                },
                axisTick: {
                    show: false
                },
                splitLine: {
                    show: false
                },
                axisLabel: {
                    show: false
                },
                detail: {
                    show: false
                },
                data: [
                    {
                        value: res.value.temperature
                    }
                ]
            }
        ]
    };
    setInterval(function () {
        const random = res.value.temperature;
        myChart.setOption({
            series: [
                {
                    data: [
                        {
                            value: random
                        }
                    ]
                },
                {
                    data: [
                        {
                            value: random
                        }
                    ]
                }
            ]
        });
    }, 1000);

    option && myChart.setOption(option);
}
// 湿度仪表盘
const humidityInit = (res) => {
    let chartDom = document.getElementById('humidity');
    let myChart = proxy.$echarts.init(chartDom);
    let ro = new ResizeObserver((entries) => {
        myChart.resize();
    });
    ro.observe(chartDom);
    let option;

    option = {
        series: [
            {
                type: 'gauge',
                radius: '80%',
                progress: {
                    show: true,
                    width: 18
                },
                axisLine: {
                    lineStyle: {
                        width: 18
                    }
                },
                axisTick: {
                    show: false
                },
                splitLine: {
                    length: 10,
                    lineStyle: {
                        width: 2,
                        color: '#999'
                    }
                },
                axisLabel: {
                    distance: 25,
                    color: '#999',
                    fontSize: 15
                },
                anchor: {
                    show: true,
                    showAbove: true,
                    size: 25,
                    itemStyle: {
                        borderWidth: 10
                    }
                },
                title: {
                    show: false
                },
                detail: {
                    valueAnimation: true,
                    fontSize: 20,
                    offsetCenter: [0, '70%']
                },
                data: [
                    {
                        value: res.value.humidity
                    }
                ]
            }
        ]
    };

    option && myChart.setOption(option);
}
// 温湿度折线图
const tempAndHumLineInit = (res) => {
    let chartDom = document.getElementById('tempAndHumLine');
    let myChart = proxy.$echarts.init(chartDom);
    let ro = new ResizeObserver((entries) => {
        myChart.resize();
    });
    ro.observe(chartDom);
    let option;
    let arr1 = [];
    let arr2 = [];
    let arr3 = [];
    res.value.forEach((item) => {
        arr1.push(item.avgtemp);
        arr2.push(item.avghumi);
        arr3.push(formatTime(new Date(item.create_time)).substring(11))
    })
    


    option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                crossStyle: {
                    color: '#999'
                }
            }
        },
        // legend: {
        //     data: ['温度', '湿度'],
        //     right: 0,
        // },
        xAxis: [
            {
                type: 'category',
                // data: ['2016-3', '2016-4', '2016-5', '2016-6', '2016-7', '2016-8', '2016-9'],
                data: arr3,
                axisPointer: {
                    type: 'shadow'
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                // name: '',
                min: 0,
                max: 80,
                interval: 20,
                axisLabel: {
                    formatter: '{value} °C'
                }
            },
            {
                type: 'value',
                // name: '',
                min: 0,
                max: 100,
                interval: 25,
                axisLabel: {
                    formatter: '{value} %'
                }
            }
        ],
        series: [
            {
                // name: '温度',
                type: 'line',
                color: '#D86E6C',
                tooltip: {
                    valueFormatter: function (value) {
                        return value + ' ml';
                    }
                },
                data: arr1,
                // data: [
                //     2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3
                // ]
            },
            {
                // name: '湿度',
                type: 'line',
                color: '#5B6BB5',
                yAxisIndex: 1,
                tooltip: {
                    valueFormatter: function (value) {
                        return value + ' %';
                    }
                },
                data: arr2
                // data: [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2]
            }
        ]
    };

    option && myChart.setOption(option);
}

//数据统计
const dataStatisInit = (res) => {
    let chartDom = document.getElementById('dataStatis');
    let myChart = echarts.init(chartDom);
    let ro = new ResizeObserver((entries) => {
        myChart.resize();
    });
    ro.observe(chartDom);
    var option;

    let data = [];
    let data1 = [];
    let data2 = [];
    res.value.forEach((item) => {
        data.push(item.avgtemp);
        data1.push(item.avghumi-item.avgtemp);
        data2.push(formatTime(new Date(item.create_time)).substring(11))
    })
    option = {
        // title: {
        //     left: 'center',
        //     text: ''
        // },
        // legend: {
        //     top: 'bottom',
        //     data: ['Intention']
        // },
        tooltip: {
            triggerOn: 'none',
            position: function (pt) {
                return [pt[0], 130];
            }
        },
        xAxis: {
            type: 'category',
            data: data2,
        },
        yAxis: [
            {
                type: 'value',
                color: '#D86E6C',
                min: 0,
                max: 80,
                interval: 20,
                splitLine: {
                    show: false
                },
                axisLabel: {
                    inside: true,
                    formatter: '{value}℃'
                },
                data: data,
            },
            {
                type: 'value',
                color: '#5B6BB5',
                min: 0,
                max: 100,
                interval: 25,
                splitLine: {
                    show: false
                },
                yAxisIndex: 1,
                axisLabel: {
                    inside: true,
                    formatter: '{value}%'
                },
                data: data1
            }
        ],
        grid: {
            top: 110,
            left: 15,
            right: 15,
            bottom: 20,
        },
        dataZoom: [
            {
                type: 'inside',
                throttle: 50
            }
        ],
        series: [
            {
                name: 'Fake Data',
                type: 'line',
                smooth: true,
                stack: 'a',
                symbol: 'circle',
                symbolSize: 4,
                sampling: 'average',
                itemStyle: {
                    color: '#F2597F'
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: 'rgba(213,72,120,0.8)'
                        },
                        {
                            offset: 1,
                            color: 'rgba(213,72,120,0.3)'
                        }
                    ])
                },
                data: data
            },
            {
                name: 'Fake Data',
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 4,
                sampling: 'average',
                itemStyle: {
                    color: '#0770FF'
                },
                stack: 'a',
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: 'rgba(58,77,233,0.8)'
                        },
                        {
                            offset: 1,
                            color: 'rgba(58,77,233,0.3)'
                        }
                    ])
                },
                data: data1
            },
            
        ]
    };

    option && myChart.setOption(option);
}

// 树形选择
const handleNodeClick = (data) => {
    console.log('data', data);
}

const data = [
    {
        id: 1,
        label: 'Level one 1',
        children: [
            {
                id: 4,
                label: 'Level two 1-1',
                children: [
                    {
                        id: 9,
                        label: 'Level three 1-1-1',
                    },
                    {
                        id: 10,
                        label: 'Level three 1-1-2',
                    },
                ],
            },
        ],
    },
    {
        id: 2,
        label: 'Level one 2',
        children: [
            {
                id: 5,
                label: 'Level two 2-1',
            },
            {
                id: 6,
                label: 'Level two 2-2',
            },
        ],
    },
    {
        id: 3,
        label: 'Level one 3',
        children: [
            {
                id: 7,
                label: 'Level two 3-1',
            },
            {
                id: 8,
                label: 'Level two 3-2',
            },
        ],
    },
]

const defaultProps = {
    children: 'children',
    label: 'label',
}
</script>

<style lang="scss" scoped>
.dataView {
    margin: 0 10px;
    height: 92vh;
    min-width: 765px;

    .main_left {
        flex: 2;
        height: 92vh;
        margin-right: 10px;
        padding: 16px;
        box-sizing: border-box;
    }

    .main_right {
        flex: 12;
        min-width: 540px;

        .main-right-tit {
            height: 39px;
        }

        .main-right-center {
            min-height: 450px;
            // height: 44vh;
            margin-top: 4px;
            padding-right: 10px;

            .main-right-center_l {
                .radius-top {
                    border-top-left-radius: 8px;
                    border-top-right-radius: 8px;

                    .temp_box {

                        .cav-box {
                            width: 90%;
                            height: 80%;
                            margin: 0 auto;
                            min-height: 300px;
                        }
                    }
                }

                .radius-bot {
                    border-bottom-left-radius: 8px;
                    border-bottom-right-radius: 8px;
                }
            }


            .main-right-center_r {
                .cav-box {
                    width: 90%;
                    height: 80%;
                    margin: 0 auto;
                    min-height: 300px;
                }
            }

        }

        .main-right-bottom {
            min-height: 324px;
            min-width: 998px;
            height: 44vh;
            margin-top: 10px;

            .select-time {
                width: 74px;
                height: 28px;
                line-height: 28px;
                margin-right: 15px;
                border: 1px solid #1890FF;
                font-size: 13px;
            }

            .selBgc {
                background-color: #1890FF;
                color: #fff;
            }
        }
    }

    .icon_el {
        padding-top: 5px;
        padding-left: 5px;
    }
}
</style>
<style lang="scss" scoped>
@media (max-width:1500px) {
    .main-right-center_l {
        flex: 0 0 100% !important;
        max-width: 100% !important;
        min-width: 610px;
        margin-bottom: 10px;
    }

    .main-right-center_r {
        flex: 0 0 100% !important;
        max-width: 100% !important;
        min-width: 610px;
        margin: 0 10px;
    }
}
</style>
<!-- 去掉el-input为number时右边的微调器 -->
<style lang="scss" scoped>
:deep input::-webkit-outer-spin-button,
:deep input::-webkit-inner-spin-button {
    -webkit-appearance: none !important;
}

:deep input[type="number"] {
    -moz-appearance: textfield !important;
}
</style>
